package com.myblog.filter;

import com.alibaba.fastjson.JSON;
import com.myblog.Utils.JwtUtil;

import com.myblog.Utils.RedisCache;
import com.myblog.Utils.WebUtils;
import com.myblog.domain.GlobalResponse;
import com.myblog.domain.entity.LoginUser;
import com.myblog.domain.entity.enums.GlobalResponseEnum;
import com.myblog.expection.GlobalException;
import io.jsonwebtoken.Claims;
import org.springframework.context.annotation.ComponentScan;
import org.springframework.security.authentication.UsernamePasswordAuthenticationToken;
import org.springframework.security.core.context.SecurityContextHolder;
import org.springframework.stereotype.Component;
import org.springframework.util.StringUtils;
import org.springframework.web.filter.OncePerRequestFilter;

import javax.annotation.Resource;
import javax.servlet.FilterChain;
import javax.servlet.ServletException;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import java.io.IOException;
import java.util.Objects;

@Component
public class JwtAuthenticationTokenFilter extends OncePerRequestFilter {
    @Resource
    RedisCache redisCache;
    @Override
    protected void doFilterInternal(HttpServletRequest httpServletRequest, HttpServletResponse httpServletResponse, FilterChain filterChain) throws ServletException, IOException {
        //获取请求头中的token
        String token = httpServletRequest.getHeader("token");
        //token没有的话说明该接口不需要已登录,直接放行
        if(!StringUtils.hasText(token)){
            filterChain.doFilter(httpServletRequest,httpServletResponse);
            return;
        }
        //解析获取userid
        Claims claims =null;
        try {
            claims= JwtUtil.parseJWT(token);
        } catch (Exception e) {
            e.printStackTrace();

            // token超时 token违法 响应回前端
            GlobalResponse result = GlobalResponse.error(GlobalResponseEnum.NEED_LOGIN);
            WebUtils.renderString(httpServletResponse,JSON.toJSONString(result));


        }
        String userid = claims.getSubject();

        //从redis中获取信息
        LoginUser loginUser = redisCache.getCacheObject("adminLogin:"+userid);
        //
        if(Objects.isNull(loginUser)){
            GlobalResponse result = GlobalResponse.error(GlobalResponseEnum.NEED_LOGIN.getCode(),"该用户信息不存在");
            WebUtils.renderString(httpServletResponse,JSON.toJSONString(result));
            return;
        }
        //存入SecurityContextHolder
        UsernamePasswordAuthenticationToken authenticationToken=new UsernamePasswordAuthenticationToken(loginUser,null,null);
        SecurityContextHolder.getContext().setAuthentication(authenticationToken);
        filterChain.doFilter(httpServletRequest,httpServletResponse);
    }
}
